/**
 * 按需引入 js方法封装处理  utils
 */

/**
 * @function 计算获取小时前几分钟前
 */
export function todo_time(time) {
  if (!time) {
    return "";
  }
  var oDate = new Date();
  var newHaoMiao1 = oDate.getTime(); //当前时间,含有时分秒
  oDate.setHours(0);
  oDate.setMinutes(0);
  oDate.setSeconds(0);
  oDate.setMilliseconds(0);
  var newHaoMiao2 = oDate.getTime(); //当前时间,不含有时分秒
  var newTime = time.replace(new RegExp("-", "gm"), "/");
  var arrTime = time.substring(0, 11).replace(new RegExp("-", "gm"), "/"); //截取时间，不含有时分秒
  var showTime = time.substring(0, 11);
  var oldHaoMiao1 = new Date(newTime).getTime(); //含有时分秒的转化成毫秒
  var oldHaoMiao2 = new Date(arrTime).getTime(); //不含有时分秒的转化成毫秒
  var d1 = (newHaoMiao1 - oldHaoMiao1) / 1000;
  var d2 = (newHaoMiao2 - oldHaoMiao2) / 1000;
  var d_result = "";
  if (d2 > 0) {
    //是几天前
    var d_days = parseInt(d2 / 86400);
    if (d_days === 1) {
      d_result = "昨天";
    } else if (d_days >= 2) {
      d_result = showTime;
    }
  } else {
    //是今天
    var d_hours = parseInt(d1 / 3600);
    var d_minutes = parseInt(d1 / 60);
    if (d_hours > 0) {
      d_result = d_hours + "小时前";
    } else if (d_hours <= 0 && d_minutes > 0) {
      d_result = d_minutes + "分钟前";
    } else {
      d_result = "刚刚";
    }
  }
  return d_result;
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
  let config = {
    id: id || "id",
    parentId: parentId || "parentId",
    childrenList: children || "children",
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
  let search = params;
  search.params =
    typeof search.params === "object" &&
    search.params !== null &&
    !Array.isArray(search.params)
      ? search.params
      : {};
  dateRange = Array.isArray(dateRange) ? dateRange : [];
  if (typeof propName === "undefined") {
    search.params["beginTime"] = dateRange[0];
    search.params["endTime"] = dateRange[1];
  } else {
    search.params["begin" + propName] = dateRange[0];
    search.params["end" + propName] = dateRange[1];
  }
  return search;
}

// 数据合并
export function mergeRecursive(source, target) {
  for (var p in target) {
    try {
      if (target[p].constructor == Object) {
        source[p] = mergeRecursive(source[p], target[p]);
      } else {
        source[p] = target[p];
      }
    } catch (e) {
      source[p] = target[p];
    }
  }
  return source;
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
  var actions = [];
  var currentSeparator = undefined === separator ? "," : separator;
  var temp = value.split(currentSeparator);
  Object.keys(value.split(currentSeparator)).some((val) => {
    Object.keys(datas).some((key) => {
      if (datas[key].value == "" + temp[val]) {
        actions.push(datas[key].label + currentSeparator);
      }
    });
  });
  return actions.join("").substring(0, actions.join("").length - 1);
}

/**
 * @function 校验数组对象是否填写
 */
export function verifyFill(arr, tableCol) {
  let soul = {
    state: false,
    message: "",
  };
  if (!arr.length) {
    soul.state = true;
    soul.message = "表格未填写";
  }
  arr.forEach((item, index) => {
    for (const key in tableCol) {
      if (!item[key] && item[key] !== 0) {
        soul.state = true;
        soul.message =
          soul.message + `第${1 + index}行，第${tableCol[key]}列不能为空；`;
      }
    }
  });
  return soul;
}

/**
 * @function 当结构树children为空数组的时候重置为undefined
 * @param {Array} cityData 结构树
 * 嵌套固定为 children。 type为3 filter 按钮
 */
export function mapTree(cityData) {
  if (!cityData || !cityData.length) {
    return;
  }
  for (let i = 0; i < cityData.length; i++) {
    const child = cityData[i].children;
    if (child && child.length > 0 && child[0].type !== 3) {
      mapTree(child);
    } else {
      cityData[i].children = undefined;
    }
  }
  return cityData;
}

// 验证是否为blob格式
export async function blobValidate(data) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
  let result = "";
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && typeof value !== "undefined" && value !== "") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && typeof value[key] !== "undefined" && value !== "") {
            let params = propName + "[" + key + "]";
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
}
